package com.ews.onlineexchange.exception;

import javax.enterprise.context.NonexistentConversationException;
import javax.faces.FacesException;
import javax.faces.application.ViewExpiredException;
import javax.faces.context.ExceptionHandler;
import javax.faces.context.ExceptionHandlerWrapper;
import javax.faces.context.FacesContext;
import javax.faces.event.ExceptionQueuedEvent;
import javax.faces.event.ExceptionQueuedEventContext;
import java.io.FileNotFoundException;
import java.util.Iterator;

/**
 * @program: SdewsOnlineExchange_dys
 * @description: exception处理
 * @author: wangchangqing
 * @create: 2020-11-19 10:13
 **/
public class CustomExcepetionHandler extends ExceptionHandlerWrapper {
    private static final long			serialVersionUID	= 1L;


    private ExceptionHandler wrapped;

    public CustomExcepetionHandler(ExceptionHandler wrapped) {
        this.wrapped = wrapped;
    }

    @Override
    public ExceptionHandler getWrapped() {
        return this.wrapped;
    }

    @Override
    public void handle()
            throws FacesException {
        for (Iterator<ExceptionQueuedEvent> i =
             getUnhandledExceptionQueuedEvents().iterator();
             i.hasNext();) {
            ExceptionQueuedEvent event = i.next();
            ExceptionQueuedEventContext context =
                    (ExceptionQueuedEventContext) event.getSource();
            Throwable t = context.getException();
            String cause = t.toString();
            System.out.println(cause);
            if (t instanceof FileNotFoundException || cause.indexOf("java.io.FileNotFoundException") !=-1) {
                FacesContext fc = FacesContext.getCurrentInstance();
                try {
                    if (!fc.getExternalContext().isResponseCommitted()) {
                        fc.getExternalContext().redirect(fc.getExternalContext().getApplicationContextPath()+"/404.xhtml");
                    }
                    fc.renderResponse();
                    break;
                } catch (Exception ex) {
                    throw new FacesException(ex);
                } finally {
                    i.remove();
                }
            }else if (t instanceof ViewExpiredException
                    || t instanceof NonexistentConversationException || cause.indexOf("org.jboss.weld.context.NonexistentConversationException") !=-1) {

                FacesContext fc = FacesContext.getCurrentInstance();
                try {
                    if (!fc.getExternalContext().isResponseCommitted()) {
                        fc.getExternalContext().redirect(fc.getExternalContext().getApplicationContextPath()+"/expiredView.xhtml");
                    }
                    fc.renderResponse();
                    break;
                } catch (Exception ex) {
                    throw new FacesException(ex);
                } finally {
                    i.remove();
                }
            }

        }
        getWrapped().handle();
    }
}
